/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import beans.FormacaoAcademica;
import beans.Identificacao;
import beans.InformacoesPessoais;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;

/**
 *
 * @author arthur
 */
public class Login extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        try {
            Identificacao identificacao = new Identificacao();
            String url = null;
            String email = request.getParameter("email");
            String senha = request.getParameter("senha");

            identificacao.setEmail(email);
            identificacao.setSenha(senha);

            String fileLocation = getServletContext().getRealPath("/dados");
            
            if (validateLogin(fileLocation + "/login.obj", identificacao)) {
                HttpSession session = request.getSession();
                session.setAttribute("identificacao", identificacao);
                loadData(fileLocation + "/" + identificacao.getEmail(), session);
                url = "/inicio.jsp";
            } else {
                JOptionPane.showMessageDialog(null, "Usuario e/ou senha inválidos. Cheque as informações, ou cadastre-se");
                url = "/login.jsp";
            }
            RequestDispatcher dispatcher = request.getRequestDispatcher(url);
            dispatcher.forward(request, response);
        } catch (ServletException ex) {
            JOptionPane.showMessageDialog(null, "EXCEPTION NO SERVLETEXCEPTION"
                    + " DO LOGIN");
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "EXCEPTION NO DISPATCH DO LOGIN");

        }

    }

    public boolean validateLogin(String fileLocation, Identificacao id) {
        List<Identificacao> users = readUserList(fileLocation);
        for (int i = 0; i < users.size(); i++) {
            if (users.get(i).getEmail().equals(id.getEmail())
                    && users.get(i).getSenha().equals(id.getSenha())) {
                return true;
            }
        }
        return false;
    }

    public void loadData(String fileLocation, HttpSession session) {

        //instanciar os beans
        //ler os dados dos arquivos e setar nos beans
        InformacoesPessoais informacoesPessoais = readInformacoes(fileLocation + "_informacoesPessoais.obj");

        List<FormacaoAcademica> formacoesAcademicas = readFormAcademicaList(fileLocation+"_formacoesAcademicas.obj");

        //salvar beans na sessao
        if (informacoesPessoais!= null) {
            session.setAttribute("informacoesPessoais", informacoesPessoais);
        }
        if(formacoesAcademicas !=null){
            
            session.setAttribute("formacoesAcademicas", formacoesAcademicas);
        }
    }

    public InformacoesPessoais readInformacoes(String fileLocation) {
        InformacoesPessoais infoPessoais = new InformacoesPessoais();
        ObjectInputStream objIn = null;
        try {
            objIn = new ObjectInputStream(new FileInputStream(fileLocation));
            //put into arrayList
            infoPessoais = (InformacoesPessoais) objIn.readObject();
        } catch (IOException e) {
            return infoPessoais;
        } catch (ClassNotFoundException e) {
        } finally {
            if (objIn != null) {
                try {
                    objIn.close();
                    return infoPessoais;
                } catch (IOException e) {
                }
            }
        }
        return null;
    }

    public List<FormacaoAcademica> readFormAcademicaList(String fileLocation) {
        List<FormacaoAcademica> formacoes = new ArrayList<>();
        ObjectInputStream objIn = null;
        try {
            objIn = new ObjectInputStream(new FileInputStream(fileLocation));
            //put into arrayList
            formacoes = (List<FormacaoAcademica>) objIn.readObject();
        } catch (IOException e) {
        } catch (ClassNotFoundException e) {
        } finally {
            if (objIn != null) {
                try {
                    objIn.close();
                    return formacoes;
                } catch (IOException e) {
                }
            }
        }
        return null;
    }

    public List<Identificacao> readUserList(String fileLocation) {
        List<Identificacao> users = new ArrayList<>();
        ObjectInputStream objIn = null;
        try {
            objIn = new ObjectInputStream(new FileInputStream(fileLocation));
            //put into arrayList
            users = (List<Identificacao>) objIn.readObject();
        } catch (IOException e) {
        } catch (ClassNotFoundException e) {
        } finally {
            if (objIn != null) {
                try {
                    objIn.close();
                    return users;
                } catch (IOException e) {
                }
            }
        }
        return null;
    }
}
